package com.jifeng.br.pjj.bookreader.util.shiro;

import com.alibaba.fastjson.JSON;
import com.jifeng.br.pjj.bookreader.util.R;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author PangJunjie
 * @Date 2023/7/12/012
 */
public class Shiro2Filter extends AuthenticatingFilter {

    /*获取或创建用于Shiro的token*/
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = getTokenString(servletRequest);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return new Shiro2Token(token);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = getTokenString(servletRequest);
        /*转换request和response*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /*处理中文乱码*/
        response.setContentType("application/json;charset=utf-8");
        /*解决跨域*/
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        if (StringUtils.isEmpty(token)) {
            response.getWriter().println(JSON.toJSON(R.error(401, "未携带token")));
            return false;
        }
        /*放行*/
        return executeLogin(servletRequest, servletResponse);
    }

    /*屏蔽无意义的option请求*/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        return httpRequest.getMethod().equals(RequestMethod.OPTIONS.name());
    }

    private String getTokenString(ServletRequest servletRequest) {
        /*转换request*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        /*从请求头中获取token*/
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        return token;
    }
}
